<template>
  <el-dialog
    :model-value="visible"
    :title="`“${propertyName}” 的评论`"
    width="50%"
    @update:model-value="$emit('update:visible', $event)"
    @open="loadReviews"
    top="10vh"
    destroy-on-close
  >
    <div v-loading="propertyStore.reviewsLoading" style="min-height: 200px;">
      <div v-if="!propertyStore.reviewsLoading">
        <el-empty v-if="!propertyStore.currentPropertyReviews.length" description="暂无评论" />
        <div v-else class="review-list-container">
          <el-card v-for="review in propertyStore.currentPropertyReviews" :key="review.id" class="review-card">
            <div class="review-header">
              <span class="review-username">{{ review.user.username }}</span>
              <el-rate v-model="review.rating" disabled size="small"/>
            </div>
            <p class="review-comment">{{ review.comment }}</p>
            <div class="review-footer">
              <span class="review-timestamp">{{ formatTime(review.created_at) }}</span>
            </div>
          </el-card>
        </div>
      </div>
    </div>
     <template #footer>
      <span class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue';
import { usePropertyStore } from '@/stores/properties';
import dayjs from 'dayjs';

const props = defineProps({
  propertyId: {
    type: Number,
    required: true,
  },
  propertyName: {
    type: String,
    default: '该房源'
  },
  visible: {
    type: Boolean,
    required: true,
  },
});

defineEmits(['update:visible']);

const propertyStore = usePropertyStore();

// 当对话框打开时，加载评论
const loadReviews = () => {
  if (props.propertyId) {
    propertyStore.fetchReviewsForProperty(props.propertyId);
  }
};

const formatTime = (isoString) => {
  if (!isoString) return '';
  // 使用 dayjs 解析 ISO 字符串，并格式化为您想要的样子
  // 'YYYY-MM-DD HH:mm:ss' 是最常用的格式
  return dayjs(isoString).format('YYYY-MM-DD HH:mm:ss');
};

</script>

<style scoped>
.review-list-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}
.review-card {
  margin-bottom: 15px;
}
.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.review-username {
  font-weight: bold;
}
.review-comment {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin: 0 0 8px 0;
  white-space: pre-wrap; /* 保留换行和空格 */
}
.review-footer {
  text-align: right;
}
.review-timestamp {
  font-size: 12px;
  color: #999;
}
</style>